import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
// import 'package:cookie_jar/cookie_jar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';

// import 'package:path_provider/path_provider.dart';
// import 'package:weshop_crm/util/event_bus_util.dart';

export 'package:dio/dio.dart' show RequestOptions, DioError;

const int HTTP_FMT_ERROR_CODE = -1;
const String HTTP_BUS_ERROR_MESSAGE = '服务器开小差了,稍后再试';

const String HTTP_ERROR_CODE_KEY = 'code';
const String HTTP_ERROR_MESSAGE_KEY = 'message';
const String HTTP_RESP_ERROR_KEY = 'error';
const String HTTP_RESP_RESULT_KEY = 'result';
const String HTTP_RESP_SUCCESS_KEY = 'success';

const String PDA_RESP_SUCCESS_KEY = 'success';
const String PDA_RESP_MESSAGE_KEY = 'returnMessage';

const BASE_URL = 'http://pre.psi.weshop-corp.com';

class PDARequest {
  Dio _dio;
  static PDARequest _instance;

  factory PDARequest() => PDARequest._getInstance();

  static PDARequest get instance => PDARequest._getInstance();

  PDARequest._() {
    _dio = Dio(BaseOptions(
      baseUrl: BASE_URL,
      method: 'post',
      connectTimeout: 30 * 1000,
      receiveTimeout: 30 * 1000,
      headers: {'user-agent': 'crm4mobile/channel/1.0.0'},
    ));
    _dio.transformer = DefaultTransformer(jsonDecodeCallback: (data) {
      try {
        return json.decode(data);
      } catch (error, stack) {
        debugPrint('transformer body error: $error');
        debugPrint(stack.toString());
        return null;
      }
    });
    _dio.interceptors.add(
      InterceptorsWrapper(onRequest: (RequestOptions options) async {
        return options;
      }, onResponse: (Response response) async {
        if (response.statusCode == 200 &&
            !response.data[PDA_RESP_SUCCESS_KEY]) {
          throw response.data[PDA_RESP_MESSAGE_KEY];
        }
        return response;
      }, onError: (DioError e) async {
        return e;
      }),
    );
  }

  static PDARequest _getInstance() {
    if (_instance == null) {
      _instance = PDARequest._();
    }
    return _instance;
  }

  // void _sendSeesionInvalid() {
  //   EventBusUtil().fire(SeesionInvaildEvent());
  // }

  // Future<void> setupCookie() async {
  //   //add cookie
  //   Directory appDocDir = await getApplicationDocumentsDirectory();
  //   String appDocPath = appDocDir.path;
  //   var cookieJar = PersistCookieJar(dir: appDocPath + "/.cookies/");
  //   _dio.interceptors.add(CookieManager(cookieJar));
  // }

  // void setProxy() {
  //   (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
  //       (HttpClient client) {
  //     client.findProxy = (uri) {
  //       return 'PROXY 172.21.12.129:8888';
  //     };
  //     client.badCertificateCallback =
  //         (X509Certificate cert, String host, int port) => true;
  //   };
  // }

  Future<Map<String, dynamic>> post(
    String path, {
    Options options,
    Map<String, dynamic> queryParameters = const {},
  }) async {
    Response<Map<String, dynamic>> response =
        await _dio.post<Map<String, dynamic>>(path,
            data: queryParameters, options: options);
    var data = response.data;
    return data;
  }

  Future<Map<String, dynamic>> get(
    String path, {
    Options options,
    Map<String, dynamic> queryParameters,
  }) async {
    Response<Map<String, dynamic>> response =
        await _dio.get<Map<String, dynamic>>(
      path,
      queryParameters: queryParameters,
      options: options,
    );
    var data = response.data;
    return data;
  }
}

/// 请求接口返回错误
class MOAError {
  final int code;
  final String message;

  const MOAError({this.code = 0, this.message});

  factory MOAError.error(Map<String, dynamic> map) {
    var code = map[HTTP_ERROR_CODE_KEY] ?? -1;
    var message = map[HTTP_ERROR_MESSAGE_KEY] ?? '未知错误请稍后再试';
    return MOAError(code: code ?? -1, message: message);
  }

  @override
  String toString() {
    return 'MwpError{code: $code, message: $message}';
  }
}
